"""缓存管理API端点"""

from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, Any
import logging

from app.services.chroma_cache_service import chroma_cache_service
from app.configs.redis_config import redis_manager
from app.api.endpoints.auth import get_current_user
from app.models import User

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/cache", tags=["Cache Management"])


@router.get("/stats")
async def get_cache_stats(current_user: User = Depends(get_current_user)) -> Dict[str, Any]:
    """获取缓存统计信息"""
    try:
        stats = chroma_cache_service.get_cache_stats()
        return {
            "success": True,
            "data": stats
        }
    except Exception as e:
        logger.error(f"获取缓存统计失败: {e}")
        raise HTTPException(status_code=500, detail="获取缓存统计失败")


@router.delete("/user/{user_id}")
async def clear_user_cache(
    user_id: str,
    current_user: User = Depends(get_current_user)
) -> Dict[str, Any]:
    """清除指定用户的缓存"""
    try:
        # 检查权限：只能清除自己的缓存，或者管理员可以清除任何用户的缓存
        if current_user.id != user_id and not getattr(current_user, 'is_admin', False):
            raise HTTPException(status_code=403, detail="无权限清除其他用户的缓存")
        
        success = chroma_cache_service.invalidate_user_cache(user_id)
        
        return {
            "success": success,
            "message": f"用户 {user_id} 的缓存已清除" if success else "清除缓存失败"
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"清除用户缓存失败: {e}")
        raise HTTPException(status_code=500, detail="清除用户缓存失败")


@router.delete("/knowledge")
async def clear_knowledge_cache(current_user: User = Depends(get_current_user)) -> Dict[str, Any]:
    """清除知识检索缓存"""
    try:
        success = chroma_cache_service.invalidate_knowledge_cache()
        
        return {
            "success": success,
            "message": "知识检索缓存已清除" if success else "清除缓存失败"
        }
    except Exception as e:
        logger.error(f"清除知识缓存失败: {e}")
        raise HTTPException(status_code=500, detail="清除知识缓存失败")


@router.delete("/all")
async def clear_all_cache(current_user: User = Depends(get_current_user)) -> Dict[str, Any]:
    """清除所有缓存（需要管理员权限）"""
    try:
        # 检查管理员权限
        if not getattr(current_user, 'is_admin', False):
            raise HTTPException(status_code=403, detail="需要管理员权限")
        
        success = redis_manager.flushdb()
        
        return {
            "success": success,
            "message": "所有缓存已清除" if success else "清除缓存失败"
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"清除所有缓存失败: {e}")
        raise HTTPException(status_code=500, detail="清除所有缓存失败")


@router.get("/redis/info")
async def get_redis_info(current_user: User = Depends(get_current_user)) -> Dict[str, Any]:
    """获取Redis服务器信息"""
    try:
        info = redis_manager.get_info()
        return {
            "success": True,
            "data": info
        }
    except Exception as e:
        logger.error(f"获取Redis信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取Redis信息失败")


@router.post("/redis/test")
async def test_redis_connection(current_user: User = Depends(get_current_user)) -> Dict[str, Any]:
    """测试Redis连接"""
    try:
        # 测试写入
        test_key = f"test:connection:{current_user.id}"
        test_value = "connection_test"
        
        write_success = redis_manager.set(test_key, test_value, expire=60)
        if not write_success:
            return {
                "success": False,
                "message": "Redis写入测试失败"
            }
        
        # 测试读取
        read_value = redis_manager.get(test_key)
        if read_value != test_value:
            return {
                "success": False,
                "message": "Redis读取测试失败"
            }
        
        # 测试删除
        delete_success = redis_manager.delete(test_key)
        
        return {
            "success": True,
            "message": "Redis连接测试成功",
            "details": {
                "write": write_success,
                "read": read_value == test_value,
                "delete": delete_success
            }
        }
    except Exception as e:
        logger.error(f"Redis连接测试失败: {e}")
        raise HTTPException(status_code=500, detail=f"Redis连接测试失败: {str(e)}")


@router.get("/performance")
async def get_cache_performance(current_user: User = Depends(get_current_user)) -> Dict[str, Any]:
    """获取缓存性能指标"""
    try:
        if not redis_manager.is_available():
            return {
                "success": False,
                "message": "Redis不可用"
            }
        
        # 获取Redis信息
        redis_info = redis_manager.get_info()
        
        # 获取缓存统计
        cache_stats = chroma_cache_service.get_cache_stats()
        
        # 计算性能指标
        performance_metrics = {
            "redis_status": redis_info.get("status", "unknown"),
            "memory_usage": redis_info.get("used_memory", "unknown"),
            "total_connections": redis_info.get("connected_clients", 0),
            "total_commands": redis_info.get("total_commands_processed", 0),
            "cache_types": len(cache_stats) - 1 if "redis_info" in cache_stats else len(cache_stats),
            "total_cached_items": sum(
                stats.get("count", 0) 
                for key, stats in cache_stats.items() 
                if isinstance(stats, dict) and "count" in stats
            )
        }
        
        return {
            "success": True,
            "data": {
                "performance": performance_metrics,
                "cache_stats": cache_stats,
                "redis_info": redis_info
            }
        }
    except Exception as e:
        logger.error(f"获取缓存性能指标失败: {e}")
        raise HTTPException(status_code=500, detail="获取缓存性能指标失败")
